﻿#if UNITY_IOS || UNITY_IPHONE
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEngine;

public class TrackingPostProcessBuildiOS : MonoBehaviour
{

    private const string DefaultUserTrackingDescriptionEn = "Pressing \\\"Allow\\\" uses device info for more relevant ad content";
    private const string ConsentFlowPrivacyPolicyUrl = "https://www.hwengame.com/privacy.html"; 

    [PostProcessBuildAttribute(int.MaxValue)]
    public static void MaxPostProcessPlist(BuildTarget buildTarget, string path) {
        var plistPath = Path.Combine(path, "Info.plist");
        var plist = new PlistDocument();
        plist.ReadFromFile(plistPath);

        EnableConsentFlowIfNeeded(plist, path);

        plist.WriteToFile(plistPath);
    }

    private static void EnableConsentFlowIfNeeded(PlistDocument plist, string buildPath) {
        // Check if consent flow is enabled. No need to update info.plist if consent flow is disabled.
        var userTrackingUsageDescription = DefaultUserTrackingDescriptionEn;
        var privacyPolicyUrl =ConsentFlowPrivacyPolicyUrl;

        // We need to remove the backticks from the default user tracking usage description when adding it to the info.plist. The backticks are only required when adding to InfoPlist.strings.  
        userTrackingUsageDescription = userTrackingUsageDescription.Replace("\\", "");

        var consentFlowInfoRoot = plist.root.CreateDict("AppLovinConsentFlowInfo");
        consentFlowInfoRoot.SetBoolean("AppLovinConsentFlowEnabled", true);
        consentFlowInfoRoot.SetString("AppLovinConsentFlowPrivacyPolicy", privacyPolicyUrl);

        plist.root.SetString("NSUserTrackingUsageDescription", userTrackingUsageDescription);
    }
}
#endif